<template>
  <div class="profile-container">
    <div class="profile-content">
      <!-- 左侧头像卡片 -->
      <div class="profile-card">
        <div class="avatar-section">
          <a-avatar 
            :size="120" 
            class="avatar" 
            :src="userInfo.avatar"
            @click="handlePreviewAvatar"
          >
            {{ !userInfo.avatar ? userInfo.username?.charAt(0).toUpperCase() : '' }}
          </a-avatar>
          <a-upload
            v-if="isOwnProfile"
            name="file"
            :showUploadList="false"
            :beforeUpload="beforeUpload"
            @change="handleAvatarChange"
          >
            <a-button class="upload-btn">
              <a-icon type="camera" />
              更换头像
            </a-button>
          </a-upload>
        </div>

        <div v-if="isOwnProfile" class="action-buttons">
          <a-button type="primary" block @click="$router.push('/')">
            <a-icon type="home" />
            回到首页
          </a-button>
          <a-button block @click="$router.push('/record')">
            <a-icon type="solution" />
            答题记录
          </a-button>
          <a-button block @click="$router.push('/likes')">
            <a-icon type="heart" />
            我的点赞
          </a-button>
          <a-button block @click="$router.push('/favorites')">
            <a-icon type="star" />
            我的收藏
          </a-button>
          <a-button block @click="handleFeedback">
            <a-icon type="message" />
            意见反馈
          </a-button>
        </div>
        
        <div v-else class="action-buttons">
          <a-button type="primary" block @click="$router.push('/')">
            <a-icon type="home" />
            回到首页
          </a-button>
        </div>
      </div>

      <!-- 右侧详细信息 -->
      <div class="profile-details">
        <a-card title="个人资料" :bordered="false">
          <template slot="extra" v-if="isOwnProfile">
            <a-button type="link" @click="handleEdit">
              <a-icon type="edit" />
              编辑资料
            </a-button>
          </template>

          <div class="user-header">
            <h2 class="username">{{ userInfo.username }}</h2>
            <a-tag color="gold" class="member-tag">普通会员</a-tag>
          </div>

          <a-descriptions :column="1">
            <a-descriptions-item label="注册时间">
              <span class="join-time">
                <a-icon type="calendar" />
                {{ userInfo.registerTime }}
              </span>
            </a-descriptions-item>
            <a-descriptions-item label="性别">
              {{ userInfo.gender === '0' ? '男' : '女' }}
            </a-descriptions-item>
            <a-descriptions-item label="手机号">
              {{ userInfo.mobile }}
            </a-descriptions-item>
            <a-descriptions-item label="邮箱">
              {{ userInfo.email }}
            </a-descriptions-item>
            <a-descriptions-item label="个人简介">
              {{ userInfo.personalProfile || '这个人懒，什么都没写~' }}
            </a-descriptions-item>
          </a-descriptions>
        </a-card>

        <a-card v-if="isOwnProfile" title="账号安全" :bordered="false" class="security-card">
          <a-list :split="false">
            <a-list-item>
              <a-list-item-meta>
                <template slot="title">修改密码</template>
                <template slot="description">定期修改密码可以保护账号安全</template>
              </a-list-item-meta>
              <a-button type="link" @click="handleChangePassword">
                修改
                <a-icon type="right" />
              </a-button>
            </a-list-item>
            <a-list-item>
              <a-list-item-meta>
                <template slot="title">账号注销</template>
                <template slot="description">
                  <span class="warning-text">注销后，账号将无法恢复</span>
                </template>
              </a-list-item-meta>
              <a-button type="link" class="danger-button" @click="handleDeleteAccount">
                注销账号
                <a-icon type="right" />
              </a-button>
            </a-list-item>
          </a-list>
        </a-card>
      </div>
    </div>

    <!-- 编辑资料对话框 -->
    <a-modal
      v-model="editModalVisible"
      title="编辑个人资料"
      @ok="handleEditSubmit"
      :confirmLoading="submitLoading"
    >
      <a-form-model ref="editForm" :model="editForm" :rules="rules">
        <a-form-model-item label="用户名" prop="username">
          <a-input v-model="editForm.username" />
        </a-form-model-item>
        <a-form-model-item label="性别" prop="gender">
          <a-radio-group v-model="editForm.gender">
            <a-radio :value="0">男</a-radio>
            <a-radio :value="1">女</a-radio>
          </a-radio-group>
        </a-form-model-item>
        <a-form-model-item label="邮箱" prop="email">
          <a-input v-model="editForm.email" />
        </a-form-model-item>
        <a-form-model-item label="个人简介" prop="personalProfile">
          <a-textarea v-model="editForm.personalProfile" :rows="4" />
        </a-form-model-item>
      </a-form-model>
    </a-modal>

    <!-- 修改密码对话框 -->
    <a-modal
      v-model="passwordModalVisible"
      title="修改密码"
      @ok="handlePasswordSubmit"
      :confirmLoading="submitLoading"
    >
      <a-form-model ref="passwordForm" :model="passwordForm" :rules="passwordRules">
        <a-form-model-item label="新密码" prop="newPassword">
          <a-input-password v-model="passwordForm.newPassword" placeholder="请输入新密码" />
        </a-form-model-item>
        <a-form-model-item label="确认密码" prop="confirmPassword">
          <a-input-password v-model="passwordForm.confirmPassword" placeholder="请再次输入新密码" />
        </a-form-model-item>
      </a-form-model>
    </a-modal>

    <!-- 添加头像预览的模态框 -->
    <a-modal
      v-model="previewVisible"
      :footer="null"
      :width="400"
      @cancel="handlePreviewCancel"
    >
      <img 
        v-if="userInfo.avatar" 
        alt="avatar" 
        style="width: 100%;" 
        :src="userInfo.avatar" 
      />
      <div 
        v-else 
        class="default-avatar-preview"
      >
        {{ userInfo.username?.charAt(0).toUpperCase() }}
      </div>
    </a-modal>
  </div>
</template>

<script>
import { auth } from '@/api/auth'
import request from '@/utils/request'

export default {
  name: 'Profile',
  data() {
    // 验证确认密码
    const validateConfirmPassword = (rule, value, callback) => {
      if (value !== this.passwordForm.newPassword) {
        callback(new Error('两次输入的密码不一致'))
      } else {
        callback()
      }
    }

    return {
      editModalVisible: false,
      passwordModalVisible: false,
      submitLoading: false,
      editForm: {
        id: '',
        username: '',
        gender: 0,
        email: '',
        personalProfile: '',
        avatar: ''
      },
      passwordForm: {
        newPassword: '',
        confirmPassword: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        email: [
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        personalProfile: [
          { max: 200, message: '不能超过200个字符', trigger: 'blur' }
        ]
      },
      passwordRules: {
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请确认新密码', trigger: 'blur' },
          { validator: validateConfirmPassword, trigger: 'blur' }
        ]
      },
      userInfo: {},
      previewVisible: false, // 添加预览模态框的显示状态
      uploadLoading: false,
    }
  },
  created() {
    this.fetchUserInfo()
  },
  methods: {
    handleEdit() {
      this.editModalVisible = true
    },
    
    handleChangePassword() {
      this.passwordModalVisible = true
    },
    
    handleFeedback() {
      this.$message.info('意见反馈功能开发中...')
    },
    
    async handleEditSubmit() {
      this.$refs.editForm.validate(async valid => {
        if (valid) {
          this.submitLoading = true
          try {
            const res = await request.post('/auth/user/update', {
              id: this.userInfo.id,
              username: this.editForm.username,
              email: this.editForm.email,
              personalProfile: this.editForm.personalProfile,
              gender: this.editForm.gender
            })
            
            if (res.code === 200) {
              this.$message.success('更新成功')
              this.editModalVisible = false
              await this.fetchUserInfo()
            } else {
              this.$message.error(res.msg || '更新失败')
            }
          } catch (error) {
            console.error('更新个人资料失败:', error)
            this.$message.error('更新失败')
          } finally {
            this.submitLoading = false
          }
        }
      })
    },
    
    handlePasswordSubmit() {
      this.$refs.passwordForm.validate(async valid => {
        if (valid) {
          this.submitLoading = true
          try {
            const res = await request.post('/auth/user/update', {
              id: this.userInfo.id,
              password: this.passwordForm.newPassword
            })
            
            if (res.code === 200) {
              this.$message.success('密码修改成功')
              this.passwordModalVisible = false
              this.$refs.passwordForm.resetFields()
            } else {
              this.$message.error(res.msg || '修改失败')
            }
          } catch (error) {
            console.error('修改密码失败:', error)
            this.$message.error('修改失败')
          } finally {
            this.submitLoading = false
          }
        }
      })
    },
    
    handleDeleteAccount() {
      // 保存this引用
      const that = this
      this.$confirm({
        title: '确定要注销账号吗？',
        content: '注销后，账号将无法恢复，所有数据将被清除',
        okText: '确认注销',
        okType: 'danger',
        cancelText: '取消',
        async onOk() {
          try {
            const res = await auth.cancelAccount(that.userInfo.id)
            if (res.code === 200) {
              that.$message.success('账号已注销')
              // 清除登录信息
              localStorage.removeItem('token')
              localStorage.removeItem('loginId')
              // 触发用户信息更新
              that.$store.commit('setUserInfo', null)
              // 跳转到首页
              that.$router.push('/')
            } else {
              that.$message.error(res.message || '注销失败')
            }
          } catch (error) {
            console.error('注销账号失败:', error)
            that.$message.error('注销失败')
          }
        }
      })
    },
    
    // 获取用户信息
    async fetchUserInfo() {
      try {
        const userId = this.$route.params.id
        const res = await auth.getUserInfo(userId)
        if (res.code === 200) {
          this.userInfo = res.content
          // 初始化编辑表单数据
          this.editForm = {
            id: this.userInfo.id,
            username: this.userInfo.username,
            gender: this.userInfo.gender,
            email: this.userInfo.email,
            personalProfile: this.userInfo.personalProfile,
            avatar: this.userInfo.avatar || ''
          }
        }
      } catch (error) {
        console.error('获取用户信息失败:', error)
        this.$message.error('获取用户信息失败')
      }
    },
    
    // 添加头像预览相关方法
    handlePreviewAvatar() {
      this.previewVisible = true
    },
    
    handlePreviewCancel() {
      this.previewVisible = false
    },

    beforeUpload(file) {
      // 验证文件类型
      const isImage = file.type.startsWith('image/')
      if (!isImage) {
        this.$message.error('只能上传图片文件!')
        return false
      }
      
      // 验证文件大小（限制为2MB）
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('图片必须小于2MB!')
        return false
      }
      
      return true
    },

    async handleAvatarChange(info) {
      const { file, fileList } = info;
      
      // 只在文件状态为 uploading 且是第一次上传时处理
      if (file.status === 'uploading' && fileList.length === 1) {
        if (this.uploadLoading) return;  // 防止重复上传
        
        this.uploadLoading = true;
        try {
          // 创建FormData对象
          const formData = new FormData();
          formData.append('file', file.originFileObj);

          // 上传文件
          const uploadRes = await request.post('/oss/upload', formData, {
            headers: {
              'Content-Type': 'multipart/form-data'
            }
          });

          if (uploadRes.code === 200) {
            // 获取上传后的URL并更新头像
            const updateRes = await request.post('/auth/user/update', {
              id: this.userInfo.id,
              avatar: uploadRes.content
            });

            if (updateRes.code === 200) {
              this.$message.success('头像更新成功');
              await this.fetchUserInfo();
            } else {
              this.$message.error(updateRes.msg || '头像更新失败');
            }
          } else {
            this.$message.error(uploadRes.msg || '文件上传失败');
          }
        } catch (error) {
          console.error('头像更新失败:', error);
          this.$message.error('头像更新失败');
        } finally {
          this.uploadLoading = false;
        }
      }
    },
  },
  
  // 监听路由参数变化,重新获���用户信息
  watch: {
    '$route.params.id': {
      handler() {
        this.fetchUserInfo()
      }
    }
  },
  computed: {
    // 判断是否是查看自己的主页
    isOwnProfile() {
      return !this.$route.params.id
    }
  }
}
</script>

<style scoped>
.profile-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 24px;
}

.profile-content {
  display: flex;
  gap: 24px;
}

.profile-card {
  width: 280px;
  background: white;
  border-radius: 12px;
  padding: 32px;
  text-align: center;
  height: fit-content;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.avatar-section {
  margin-bottom: 32px;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
}

.avatar {
  background: #1890ff;
  font-size: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 4px solid #f0f7ff;
  box-shadow: 0 2px 8px rgba(24, 144, 255, 0.15);
  cursor: pointer; /* 添加鼠标手型 */
  transition: transform 0.3s ease;
}

.avatar:hover {
  transform: scale(1.05);
}

.avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.upload-btn {
  color: #8c8c8c;
  font-size: 14px;
  padding: 4px 12px;
  height: auto;
  background: #f5f5f5;
  border-radius: 4px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.upload-btn:hover {
  color: #1890ff;
  background: #e6f7ff;
}

.upload-btn .anticon {
  font-size: 16px;
}

.user-header {
  padding-bottom: 24px;
  margin-bottom: 24px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  align-items: center;
  gap: 12px;
}

.username {
  font-size: 24px;
  font-weight: 600;
  color: #1f2937;
  margin: 0;
}

.member-tag {
  font-size: 13px;
  padding: 0 8px;
  height: 22px;
  line-height: 20px;
  border-radius: 4px;
  background: #fffbe6;
  border: 1px solid #ffe58f;
  color: #d48806;
}

.join-time {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #666;
  font-size: 14px;
}

.join-time .anticon {
  color: #8c8c8c;
}

.action-buttons {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.action-buttons .ant-btn {
  height: 40px;
  font-size: 15px;
}

.profile-details {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.profile-details :deep(.ant-card) {
  border-radius: 8px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.06);
}

.profile-details :deep(.ant-card-head) {
  border-bottom: 1px solid #f0f0f0;
  padding: 0 24px;
}

.profile-details :deep(.ant-card-head-title) {
  font-size: 16px;
  font-weight: 600;
}

.profile-details :deep(.ant-descriptions-item-label) {
  color: #6b7280;
  width: 100px;
  font-size: 14px;
}

.profile-details :deep(.ant-descriptions-item-content) {
  color: #1f2937;
  font-size: 14px;
}

.security-card :deep(.ant-list-item) {
  padding: 16px 0;
}

.security-card :deep(.ant-list-item-meta-title) {
  color: #1f2937;
  font-weight: 500;
}

.security-card :deep(.ant-list-item-meta-description) {
  color: #6b7280;
}

.warning-text {
  color: #dc2626;
}

.danger-button {
  color: #dc2626;
}

.danger-button:hover {
  color: #ef4444;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .profile-content {
    flex-direction: column;
  }
  
  .profile-card {
    width: 100%;
    padding: 24px;
  }

  .profile-header {
    padding-bottom: 24px;
    margin-bottom: 24px;
  }

  .avatar {
    width: 100px;
    height: 100px;
    font-size: 40px;
  }
}

/* 添加头像相关样式 */
.default-avatar-preview {
  width: 100%;
  padding-bottom: 100%;
  background: #1890ff;
  border-radius: 50%;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 120px;
  color: #fff;
}

.default-avatar-preview::before {
  content: attr(data-letter);
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

/* 预览模态框样式 */
:deep(.ant-modal-content) {
  padding: 24px;
  border-radius: 12px;
  overflow: hidden;
}

:deep(.ant-modal-close) {
  color: rgba(0, 0, 0, 0.45);
}

:deep(.ant-modal-body) {
  padding: 0;
  line-height: 0;
}

:deep(.ant-modal-body img) {
  border-radius: 8px;
}
</style>